package com.zhaozixiang.generator.controller;

import com.zhaozixiang.generator.domain.ColumnInfo;
import freemarker.template.Configuration;
import freemarker.template.Template;
import java.io.File;
import java.io.FileWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class CodeGenerator {
    private final TableMetaDataReader metaDataReader;
    private final Configuration freemarkerConfig;

    public CodeGenerator(TableMetaDataReader metaDataReader) {
        this.metaDataReader = metaDataReader;
        this.freemarkerConfig = new Configuration(Configuration.VERSION_2_3_31);
        freemarkerConfig.setClassForTemplateLoading(this.getClass(), "/templates");
    }

    /**
     * 生成所有代码文件
     */
    public void generate(String tableName, String packageName, String outputDir) throws Exception {
        // 1. 读取表结构
        List<ColumnInfo> columns = metaDataReader.getTableColumns(tableName);
        String className = toPascalCase(tableName); // 表名 → 类名（如：user → User）

        // 2. 准备模板数据
        Map<String, Object> data = new HashMap<>();
        data.put("packageName", packageName);
        data.put("className", className);
        data.put("columns", columns);
        data.put("tableName", tableName);

        // 3. 生成文件
        generateFile("entity.ftl",    outputDir + "/domain/" + className + ".java", data);
        generateFile("mapper.ftl",   outputDir + "/mapper/" + className + "Mapper.java", data);
        generateFile("service.ftl",  outputDir + "/service/" + className + "Service.java", data);
        generateFile("mapperXml.ftl",outputDir + "/mapper/" + className + "Mapper.xml", data);
        generateFile("handler.ftl",outputDir + "/handler/" + className + "Handler.java", data);
    }

    /**
     * 表名 → 大驼峰类名（如：user_info → UserInfo）
     */
    private String toPascalCase(String tableName) {
        StringBuilder result = new StringBuilder();
        String[] parts = tableName.split("_");
        for (String part : parts) {
            result.append(part.substring(0, 1).toUpperCase())
                    .append(part.substring(1).toLowerCase());
        }
        return result.toString();
    }

    private void generateFile(String templateName, String outputPath, Map<String, Object> data) throws Exception {
        File file = new File(outputPath);
        file.getParentFile().mkdirs(); // 创建目录

        try (FileWriter writer = new FileWriter(file)) {
            Template template = freemarkerConfig.getTemplate(templateName);
            template.process(data, writer);
        }
    }
}
